<template>
  <div class="cms-tags-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>标签管理</span>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增标签
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="标签名称">
            <el-input 
              v-model="searchForm.name" 
              placeholder="请输入标签名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 标签云 -->
      <div class="tag-cloud">
        <el-tag
          v-for="tag in tableData"
          :key="tag.id"
          :type="getTagColor(tag.articleCount)"
          :size="getTagSize(tag.articleCount)"
          style="margin: 5px; cursor: pointer"
          @click="handleEdit(tag)"
        >
          {{ tag.name }} ({{ tag.articleCount }})
        </el-tag>
      </div>

      <el-divider />

      <!-- 表格区域 -->
      <el-table 
        :data="tableData" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="标签名称" width="150" />
        <el-table-column prop="slug" label="标签标识" width="150" />
        <el-table-column prop="color" label="标签颜色" width="120" align="center">
          <template #default="{ row }">
            <el-color-picker v-model="row.color" size="small" disabled />
          </template>
        </el-table-column>
        <el-table-column prop="articleCount" label="文章数" width="100" align="center" sortable>
          <template #default="{ row }">
            <el-tag :type="getTagColor(row.articleCount)">{{ row.articleCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="clickCount" label="点击数" width="100" align="center" sortable />
        <el-table-column prop="sort" label="排序" width="80" align="center" sortable />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="description" label="标签描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              link
              @click="handleEdit(row)"
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              link
              @click="handleDelete(row)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑标签弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入标签名称"
            maxlength="20"
          />
        </el-form-item>

        <el-form-item label="标签标识" prop="slug">
          <el-input 
            v-model="form.slug" 
            placeholder="请输入标签标识（英文）"
          />
          <el-text size="small" type="info">用于URL访问，如：erp、management</el-text>
        </el-form-item>

        <el-form-item label="标签颜色">
          <el-color-picker v-model="form.color" />
          <el-text size="small" type="info" style="margin-left: 10px">
            选择标签显示颜色
          </el-text>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number 
                v-model="form.sort" 
                :min="0" 
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch 
                v-model="form.status" 
                :active-value="1" 
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="标签描述">
          <el-input 
            v-model="form.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入标签描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-divider>SEO设置</el-divider>

        <el-form-item label="SEO标题">
          <el-input 
            v-model="form.seoTitle" 
            placeholder="留空则使用标签名称"
            maxlength="60"
          />
        </el-form-item>

        <el-form-item label="SEO关键词">
          <el-input 
            v-model="form.seoKeywords" 
            placeholder="多个关键词用逗号分隔"
          />
        </el-form-item>

        <el-form-item label="SEO描述">
          <el-input 
            v-model="form.seoDescription" 
            type="textarea"
            :rows="2"
            placeholder="留空则使用标签描述"
            maxlength="160"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('新增标签')
const formRef = ref()
const submitLoading = ref(false)

// 表单数据
const form = reactive({
  id: null,
  name: '',
  slug: '',
  color: '#409EFF',
  sort: 0,
  status: 1,
  description: '',
  seoTitle: '',
  seoKeywords: '',
  seoDescription: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入标签标识', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '只能包含小写字母、数字和连字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
}

// 根据文章数量获取标签颜色
const getTagColor = (count) => {
  if (count >= 50) return 'danger'
  if (count >= 20) return 'warning'
  if (count >= 10) return 'success'
  return ''
}

// 根据文章数量获取标签大小
const getTagSize = (count) => {
  if (count >= 50) return 'large'
  if (count >= 20) return 'default'
  return 'small'
}

// 查询
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  handleSearch()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增标签'
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑标签'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  if (row.articleCount > 0) {
    ElMessage.warning('该标签下还有文章，无法删除')
    return
  }

  ElMessageBox.confirm(
    `确定要删除标签"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
    loadData()
  }).catch(() => {})
}

// 状态变更
const handleStatusChange = (row) => {
  const statusText = row.status === 1 ? '启用' : '禁用'
  ElMessage.success(`已${statusText}标签：${row.name}`)
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const action = form.id ? '更新' : '新增'
        ElMessage.success(`${action}成功`)
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        ElMessage.error('操作失败：' + error.message)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
  form.id = null
  form.color = '#409EFF'
}

// 分页改变
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    tableData.value = [
      {
        id: 1,
        name: 'ERP',
        slug: 'erp',
        color: '#409EFF',
        articleCount: 68,
        clickCount: 1256,
        sort: 1,
        status: 1,
        description: 'ERP企业资源计划系统相关文章',
        createTime: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        name: '管理',
        slug: 'management',
        color: '#67C23A',
        articleCount: 45,
        clickCount: 892,
        sort: 2,
        status: 1,
        description: '企业管理相关文章',
        createTime: '2024-01-02 10:00:00'
      },
      {
        id: 3,
        name: '技术',
        slug: 'tech',
        color: '#E6A23C',
        articleCount: 32,
        clickCount: 673,
        sort: 3,
        status: 1,
        description: '技术开发相关文章',
        createTime: '2024-01-03 10:00:00'
      },
      {
        id: 4,
        name: '产品',
        slug: 'product',
        color: '#F56C6C',
        articleCount: 28,
        clickCount: 542,
        sort: 4,
        status: 1,
        description: '产品介绍相关文章',
        createTime: '2024-01-04 10:00:00'
      },
      {
        id: 5,
        name: '行业',
        slug: 'industry',
        color: '#909399',
        articleCount: 23,
        clickCount: 431,
        sort: 5,
        status: 1,
        description: '行业资讯相关文章',
        createTime: '2024-01-05 10:00:00'
      },
      {
        id: 6,
        name: '数字化',
        slug: 'digital',
        color: '#409EFF',
        articleCount: 15,
        clickCount: 328,
        sort: 6,
        status: 1,
        description: '数字化转型相关文章',
        createTime: '2024-01-06 10:00:00'
      },
      {
        id: 7,
        name: '云计算',
        slug: 'cloud',
        color: '#67C23A',
        articleCount: 12,
        clickCount: 256,
        sort: 7,
        status: 1,
        description: '云计算相关文章',
        createTime: '2024-01-07 10:00:00'
      },
      {
        id: 8,
        name: 'AI',
        slug: 'ai',
        color: '#E6A23C',
        articleCount: 9,
        clickCount: 187,
        sort: 8,
        status: 1,
        description: '人工智能相关文章',
        createTime: '2024-01-08 10:00:00'
      }
    ]
    
    pagination.total = tableData.value.length
  } catch (error) {
    ElMessage.error('加载数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.cms-tags-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
}

.tag-cloud {
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
  min-height: 100px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

